package com.fjycnet.webview;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.curry.android.util.YcToastHelper;
import com.orangelife.R;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by ZeroVoid on 2018-7-12.
 */

public class WvJsActivity extends AppCompatActivity {

    private WebView wv;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_wv_js);
        wv = findViewById(R.id.wv1);
//        String string = "<style>img{max-width:100%}</style><p><img src=\"http://p3.pstatp.com/large/pgc-image/153081390601264eebe6ee1\" img_width=\"1080\" img_height=\"720\"</p><p><img src=\"http://p9.pstatp.com/large/pgc-image/153081390632703d8f747ad\" img_width=\"640\" img_height=\"427\"/><img src=\"http://p3.pstatp.com/large/pgc-image/1530813906484932d9e09fc\" img_width=\"640\" img_height=\"427\" ></p></body>";
//        string = getNewContent(string);
        wv.loadUrl("http://www.baidu.com");
        addJs();
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        request();
                    }
                }).start();
    }

    private final String URL_TEST = "http://tg-wei.oicp.net:35910/zxm/index.php/Home/Index/test";

    private void request() {
        try {
            URL url = new URL(URL_TEST);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
//            OutputStream outStrm = connection.getOutputStream();
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                //得到响应流
                InputStream inputStream = connection.getInputStream();
                //将响应流转换成字符串
                byte[] bytes = getBytesByInputStream(inputStream);//将流转换为字符串。
                String result = new String(bytes, "UTF-8");
                Log.e(WvJsActivity.class.getSimpleName(), "result=============" + result);
                handler.sendMessage(handler.obtainMessage(1, result));
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = (String) msg.obj;
            JSONObject jo = JSON.parseObject(result);
            String url = jo.getString("url");
            wv.loadUrl(url);
            Toast.makeText(WvJsActivity.this, "url=" + url, Toast.LENGTH_SHORT).show();
            JSONArray autoScriptArray = jo.getJSONArray("autoscript");
            JSONObject jo2 = (JSONObject) autoScriptArray.get(0);
            mCheckUrl = jo2.getString("url");
            mJs = jo2.getString("script");
        }
    };

    private String mCheckUrl;
    private String mJs;

    private byte[] getBytesByInputStream(InputStream is) {
        byte[] bytes = null;
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(baos);
        byte[] buffer = new byte[1024 * 8];
        int length = 0;
        try {
            while ((length = bis.read(buffer)) > 0) {
                bos.write(buffer, 0, length);
            }
            bos.flush();
            bytes = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return bytes;
    }

    private void addJs() {
        WebSettings settings = wv.getSettings();
        settings.setJavaScriptEnabled(true);
        String name = "张统玮";
        String number = "1111111111111111";
        final String js = "javascript:document.getElementById('index-kw').value = '" + name + "';";
//        final String js = "JavaScript:function mFunc(){document.querySelector('#logo').querySelector('img').src=\"http://www.datatalking.com.cn/images/index_tip_01.jpg\";}mFunc();";


        wv.setWebViewClient(new WebViewClient() {


            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.e(WvJsActivity.class.getSimpleName(), "url=" + url);
                Log.e(WvJsActivity.class.getSimpleName(), "mCheckUrl=" + String.valueOf(mCheckUrl));
                Log.e(WvJsActivity.class.getSimpleName(), "mJs=" + String.valueOf(mJs));

                if (url != null && mCheckUrl != null && url.contains(mCheckUrl)) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        view.evaluateJavascript(mJs, new ValueCallback<String>() {
                            @Override
                            public void onReceiveValue(String s) {

                            }
                        });
                    } else {
                        view.loadUrl(mJs);
                    }
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url != null && url.contains("baiduboxapp")) {
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

        });
        wv.setWebChromeClient(new WebChromeClient() {

            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });
    }

}
